<?php
/* LDM 框架 上传类
* @Author: dm
* @Date:   2014-04-22 16:40:37
* @Last Modified by:   dm
* @Last Modified time: 2014-04-29 16:48:57
*/
class Upload{
	private $fileArr;//上传文件格式整理
	public $path;//上传文件路径
	public $isWater;//是否添加水印
	public $isThumb;//是否生成缩略图
	public $error = array();
	public function __construct($path=null,$isWater=null,$isThumb=null){
		if(empty($_FILES) || !is_array($_FILES)) return false;
		$this->format_arr();//格式化上传文件
		$this->path = is_null($path) ? C('UPLOAD_PATH') : $path;
		// var_dump($path);
		// echo $this->path;die;
		$this->path = rtrim($this->path,'/') . '/';//上传文件路径
		$this->isWater = $isWater ;
		$this->isThumb = $isThumb ;
		$this->change_path();//统一路径，让路径兼容两个系统
		is_dir($this->path) || mkdir($this->path,0777,true);//创建上传目录
	}
	/**
	 * [change_path 统一路径，让路径兼容两个系统]
	 * @return [type] [description]
	 */
	private function change_path(){
		$this->path = str_replace("\\", '/', $this->path);
		$this->path = rtrim($this->path,'/').'/';
	}
	/**
	 * [upload 上传文件]
	 * @return [array] [已上传文件信息]
	 */
	public function upload(){
		$re = array();
		if(!empty($this->fileArr)){
			$arr = $this->fileArr;
			foreach($arr as $v){
				if(is_uploaded_file($v['tmp_name'])){
					$info = pathinfo($v['name']);
					$isImage = preg_match('/image/i', $v['type']) ? 1 : 0;	//是否为图片

					$file = $this->path.time().mt_rand(0,999).'.'.$info['extension'];
					// echo ($this->path);die;
					$result = move_uploaded_file($v['tmp_name'], $file);
					//上传成功
					if($result){
						// 返回文件相对根目录路径
						$path = str_replace(ROOT_PATH, '', $file);

						// 组合单个文件上传信息
						$arr = array(
							'name'=>$info['filename'],
							'path'=> $path,
							'ext'=>$info['extension'],
							'isImage'=>$isImage,
							);

						// 上传成功，进行水印，缩略图处理
						if($isImage){
							$image = new Image();
							if($this->isWater){
								$image->water($file); 
							}
							if($this->isThumb){
								$thumb = $image->thumb($file);
								$arr['thumb'] = $thumb;
							}
							
						}
						// var_dump($arr);die;
						// 将单个文件信息压入数组
						$re[] = $arr;

					}else{
						$this->error[] = '文件'.$v['name'].'上传失败';
					}

				}else{
					$this->error[] = '文件'.$v['name'].'非法上传';
				}
			}
			
		}
		return $re;
	}
	/**
	 * [format_arr 格式化上传文件]
	 * @return [type] [void]
	 */
	private function format_arr(){
		$files = $_FILES;
		$arr = array();//将要组合返回的数组
		foreach ($files as $v) {
			if(is_array($v['name'])){
				foreach($v['name'] as $key=>$value){
					$arr[] = array(
						'name' => $value,
						'type' => $v['type'][$key],
						'tmp_name' => $v['tmp_name'][$key],
						'error' => $v['error'][$key],
						'size' => $v['size'][$key],
						);
				}
			}else{
				$arr[] = $v;
			}
		}

		$this->fileArr = $arr;
		return;
	}

}
?>
